package com.lollipop;

import com.jfinal.plugin.activerecord.dialect.Dialect;
import com.lollipop.generation.FreeMakerUtils;
import com.lollipop.generation.MetaBuilder;
import com.lollipop.generation.TableMeta;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Generater {

    DataSource ds;
    Dialect dialect;
    MetaBuilder metaBuilder;

    public static String MODEL = "model.ftl";
    public static String DAO = "dao.ftl";
    public static String MAPPER = "mapper.ftl";


    public Generater(DataSource ds, Dialect dialect) {
        this.ds = ds;
        this.dialect = dialect;
        init();
    }

    private void init() {
        this.metaBuilder = new MetaBuilder(this.ds);
        metaBuilder.setDialect(this.dialect);
        metaBuilder.build();
    }

    public void setRemovedTableNamePrefixes(String... removedTableNamePrefixes) {
        metaBuilder.setRemovedTableNamePrefixes(removedTableNamePrefixes);
    }

    /**
     * 生成代码
     *
     * @param pkgName     java的包路径com.lollipop.model
     * @param outFilePath User.java的路径如/Users/zeroleavebaoyang/Downloads
     * @param ftlName     模板名称dao.ftl, model.ftl;
     * @param suffix      生成的文件后缀名称.xml,.java,
     */
    public void generate(String pkgName, String outFilePath, String ftlName, String suffix) {
        long start = System.currentTimeMillis();
        List<TableMeta> tableMetas = metaBuilder.build();
        if (tableMetas.size() == 0) {
            System.out.println("TableMeta 数量为 0，不生成任何文件");
            return;
        }
        int i = 0;
        for (TableMeta tm : tableMetas) {
//            if (i==1) continue;
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("tableMeta", tm);
            data.put("pkgName", pkgName);
            FreeMakerUtils.generateFile(FreeMakerUtils.getFreeMarkerCfg(this.getClass(), "template"),
                    ftlName, data, outFilePath, tm.modelName + suffix);
            i++;
        }
        long usedTime = (System.currentTimeMillis() - start) / 1000;
        System.out.println("Generate complete in " + usedTime + " seconds.");
    }
}
